package cn.com.yd.commons.grpc.config;

import cn.com.yd.commons.grpc.annotation.EnableStartGrpcServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import javax.annotation.PostConstruct;

@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)
@Configuration
@ConditionalOnBean(annotation = EnableStartGrpcServer.class)
@EnableConfigurationProperties(GrpcServerProperties.class)
public class GrpcServerAutoConfiguration {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private GrpcServerProperties grpcServerProperties;

    @PostConstruct
    public void start() {
        try {
            String[] servicesName = grpcServerProperties.getServices();
            if (servicesName == null || servicesName.length < 1) {
                throw new RuntimeException("没有指定任何服务名");
            }
            Object[] os = new Object[servicesName.length];
            for (int i = 0; i < os.length; i++) {
                os[i] = this.applicationContext.getBean(servicesName[i]);
            }
            GrpcServer gs = new GrpcServer(grpcServerProperties.getEnabledSsl(), grpcServerProperties.getPort(), os);
            gs.start();
            gs.blockUntilShutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
